package com.goods.shop.controller;

import com.goods.shop.BaseController;
import com.goods.shop.annotation.Log;
import com.goods.shop.service.model.WeiXinMessageModel;
import com.goods.shop.service.model.WeiXinParam;
import com.goods.shop.service.model.WxArticle;
import com.goods.shop.service.model.wxmessage.WxTextModel;
import com.goods.shop.service.wxmessage.WxEventService;
import com.goods.shop.service.wxmessage.WxMessageService;
import com.goods.shop.util.WeiXinMessageUtils;
import com.goods.shop.util.WeiXinUtils;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class WeiXinController extends BaseController {
    @Autowired
    private WxMessageService wxMessageService;
    @Autowired
    private WxEventService wxEventService;
    @RequestMapping("/weixin")
    public String weixin(Model model, HttpServletRequest request, HttpServletResponse response){
//        SAXReader reader = new SAXReader();
//        Document document = reader.read(request.getInputStream());
        String replyMessage="";
        try {
            request.setCharacterEncoding("UTF-8");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream in=request.getInputStream();
//            String receive=new BufferedReader(new InputStreamReader(in,"UTF-8")).lines().collect(Collectors.joining(System.lineSeparator()));
//            logger.info("receive={}",receive);
//            in.reset();
            Document document = db.parse(in);
            Element root = document.getDocumentElement();
            logger.info("root.getTextContent="+root.getTextContent());

            WxTextModel entity=wxEventService.receiveEvent(root);
            logger.info("entity==={}",entity.toString());
            replyMessage=wxEventService.responseEvent(entity);
            logger.info("replyMessage={}",replyMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return replyMessage;
    }
    private List<WxArticle> generateArticles(){
        List<WxArticle> articles=new ArrayList<>();
        WxArticle article=new WxArticle();
        article.setTitle("标题1");
        article.setDescription("内容图片学习");
        article.setPicUrl("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2746890508,1411167354&fm=26&gp=0.jpg");
        article.setUrl("https://www.baidu.com");
        articles.add(article);
        article=new WxArticle();
        article.setTitle("标题2");
        article.setDescription("内容图片学习2");
        article.setPicUrl("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1169615701,2836702427&fm=26&gp=0.jpg");
        article.setUrl("https://www.jd.com");
        articles.add(article);
        return articles;
    }
    @RequestMapping("/weixin2")
    public String weixin2(Model model, @ModelAttribute("paramsModel") WeiXinParam params){
        String appid="wx5365dca5cee6faea";
        String secret="79659eb27e7b0cf00ecc1da77d659096";
        String computerSignature= WeiXinUtils.generateSignature(appid,secret,params);
        String paramsignature=params.getSignature();
        logger.info("computerSignature="+computerSignature);
        logger.info("paramsignature="+paramsignature);
        if(computerSignature.equals(paramsignature)){
            return params.getEchostr();
        }else
            return "NONE";
    }
    @RequestMapping("/receive")
    public String receive(Model model, HttpServletRequest request, HttpServletResponse response){
        String replyMsg ="";
        try {
            request.setCharacterEncoding("UTF-8");
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("text/html;charset=UTF-8");
//            PrintWriter out = response.getWriter();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(request.getInputStream());
            Element root = document.getDocumentElement();
            logger.info("root.toString={}",root.toString());
            String wechatId = root.getElementsByTagName("ToUserName").item(0).getTextContent();
            String openid = root.getElementsByTagName("FromUserName").item(0).getTextContent();
            String msg = root.getElementsByTagName("Content").item(0).getTextContent();//用户发送的内容
            logger.info("weixinsendMessage==========="+msg);//打印用户发送的消息
            String content = msg;
            long time=System.currentTimeMillis()/1000;
            replyMsg = "<xml>"
                    + "<ToUserName><![CDATA[" + openid + "]]></ToUserName>"//回复用户时，这里是用户的openid；但用户发送过来消息这里是微信公众号的原始id
                    + "<FromUserName><![CDATA[" + wechatId + "]]></FromUserName>"//这里填写微信公众号 的原始id；用户发送过来时这里是用户的openid
                    + "<CreateTime>"+time+"</CreateTime>"//这里可以填创建信息的时间，目前测试随便填也可以
                    + "<MsgType><![CDATA[text]]></MsgType>"//文本类型，text，可以不改
                    + "<Content><![CDATA[" + content + "]]></Content>"//文本内容，我喜欢你
                    + "<MsgId>1234567890123456</MsgId> "//消息id，随便填，但位数要够
                    + " </xml>";

        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return replyMsg;
    }
    @RequestMapping(value="/weixinMessageSend",method= RequestMethod.POST)
    public String sendMessage(Model model, @ModelAttribute WeiXinMessageModel messageModel){
        logger.info("messageModel={}",messageModel);
        String appId=messageModel.getAppId();
        String secret=messageModel.getSecret();
        String toUser=messageModel.getToUser();
        String templateId=messageModel.getTemplateId();
        String accessToken= WeiXinUtils.getAccessToken(appId,secret);
        String detailUrl=messageModel.getDetailUrl();
        logger.info("accessToken="+accessToken);
        String result= WeiXinMessageUtils.getAllTemplates(accessToken);
        logger.info("getAllTemplates.result={}",result);
        String message=messageModel.getMessage();
        logger.info("message={}",message);

        result= WeiXinMessageUtils.sendMessage(accessToken,toUser,templateId,message,detailUrl);
        logger.info("sendMessage.result={}",result);
        return result;
    }



}
